#!/usr/bin/env python3
"""
视频管理Web API服务
提供视频列表、播放、删除等功能
"""

from flask import Flask, jsonify, send_file, request, Response
from flask_cors import CORS
import os
from pathlib import Path
from datetime import datetime
import json

app = Flask(__name__)
CORS(app)  # 允许跨域

# 配置
VIDEO_FOLDER = Path('data/output_results')  # 视频存储路径
ALLOWED_EXTENSIONS = {'.mp4', '.avi', '.mov'}


def get_video_info(video_path):
    """获取视频文件信息"""
    try:
        stat = video_path.stat()
        filename = video_path.name

        # 解析时间（格式：danger_20231225_143052.mp4）
        try:
            parts = filename.replace('.mp4', '').split('_')
            if len(parts) >= 3:
                date_str = parts[1]
                time_str = parts[2]
                dt = datetime.strptime(f"{date_str}_{time_str}", "%Y%m%d_%H%M%S")
                display_time = dt.strftime("%Y-%m-%d %H:%M:%S")
            else:
                display_time = filename
        except:
            display_time = filename

        return {
            'filename': filename,
            'size': stat.st_size,
            'size_mb': round(stat.st_size / 1024 / 1024, 2),
            'created_time': stat.st_mtime,
            'display_time': display_time
        }
    except Exception as e:
        print(f"获取视频信息错误: {e}")
        return None


@app.route('/')
def index():
    """API根路径"""
    return jsonify({
        'status': 'running',
        'endpoints': {
            'list': '/api/videos',
            'play': '/api/video/<filename>',
            'delete': '/api/video/<filename>'
        }
    })


@app.route('/api/videos', methods=['GET'])
def get_video_list():
    """获取视频列表"""
    try:
        videos = []

        # 确保目录存在
        VIDEO_FOLDER.mkdir(parents=True, exist_ok=True)

        # 遍历视频文件
        for video_file in VIDEO_FOLDER.iterdir():
            if video_file.is_file() and video_file.suffix.lower() in ALLOWED_EXTENSIONS:
                video_info = get_video_info(video_file)
                if video_info:
                    videos.append(video_info)

        # 按创建时间倒序
        videos.sort(key=lambda x: x['created_time'], reverse=True)

        return jsonify({
            'success': True,
            'count': len(videos),
            'videos': videos
        })

    except Exception as e:
        print(f"获取视频列表错误: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/video/<filename>', methods=['GET'])
def stream_video(filename):
    """流式传输视频"""
    try:
        video_path = VIDEO_FOLDER / filename

        if not video_path.exists():
            return jsonify({'success': False, 'error': '视频不存在'}), 404

        # 获取文件大小
        file_size = video_path.stat().st_size

        # 处理Range请求
        range_header = request.headers.get('range')

        if range_header:
            # 解析range
            byte_start = 0
            byte_end = file_size - 1

            match = range_header.replace('bytes=', '').split('-')
            if match[0]:
                byte_start = int(match[0])
            if match[1]:
                byte_end = int(match[1])

            # 读取指定范围
            chunk_size = byte_end - byte_start + 1

            def generate():
                with open(video_path, 'rb') as f:
                    f.seek(byte_start)
                    remaining = chunk_size
                    while remaining > 0:
                        chunk = f.read(min(4096, remaining))
                        if not chunk:
                            break
                        remaining -= len(chunk)
                        yield chunk

            # 返回部分内容
            response = Response(
                generate(),
                status=206,
                mimetype='video/mp4'
            )
            response.headers['Content-Range'] = f'bytes {byte_start}-{byte_end}/{file_size}'
            response.headers['Accept-Ranges'] = 'bytes'
            response.headers['Content-Length'] = str(chunk_size)
            return response
        else:
            # 返回整个文件
            return send_file(
                video_path,
                mimetype='video/mp4',
                as_attachment=False
            )

    except Exception as e:
        print(f"流式传输错误: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/video/<filename>', methods=['DELETE'])
def delete_video(filename):
    """删除视频"""
    try:
        video_path = VIDEO_FOLDER / filename

        if not video_path.exists():
            return jsonify({'success': False, 'error': '视频不存在'}), 404

        # 删除文件
        video_path.unlink()

        return jsonify({
            'success': True,
            'message': f'视频 {filename} 已删除'
        })

    except Exception as e:
        print(f"删除视频错误: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


# if __name__ == '__main__':
#     print("=" * 50)
#     print("视频管理API服务")
#     print(f"视频目录: {VIDEO_FOLDER.absolute()}")
#     print("=" * 50)
#
#     # 确保视频目录存在
#     VIDEO_FOLDER.mkdir(parents=True, exist_ok=True)
#
#     # 启动服务
#     app.run(host='0.0.0.0', port=5000, debug=False)

def run_server():
    print("=" * 50)
    print("视频管理API服务")
    print(f"视频目录: {VIDEO_FOLDER.absolute()}")
    print("=" * 50)

    VIDEO_FOLDER.mkdir(parents=True, exist_ok=True)

    app.run(host='0.0.0.0', port=5000, debug=False)

if __name__ == '__main__':
    run_server()
